package com.caiheng.api.controller.user;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.caiheng.api.constant.ResponseCode;
import com.caiheng.api.controller.platform.BaseController;
import com.caiheng.api.entity.estate.Estate;
import com.caiheng.api.service.estate.EstateService;
import com.caiheng.api.util.GsonResultBean;
import com.caiheng.api.entity.wxuser.User;
import com.caiheng.api.entity.wxuser.UserAddress;
import com.caiheng.api.service.wxuser.UserAddressService;
import com.caiheng.api.service.wxuser.UserService;
import com.caiheng.api.util.Tools;

import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *@Author: ZhouWei
 *@Description:  用户技能相关接口
 *@Date 2018-05-10
 */
@Component
@RestController
@RequestMapping("/user/address")//url:模块/资源/{}/细分
public class UserAddressController extends BaseController {

    @Resource
    private UserService userService;
    @Resource
    private UserAddressService userAddressService;
    @Resource
    private EstateService estateService;


    /**我的地址列表
     * @param
     * @throws Exception
     */
    @PostMapping(value="/list")
    public JSONObject list(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;

            QueryWrapper<UserAddress> qw = new QueryWrapper<>();
            qw.eq("user_id",user_id);
            qw.orderByDesc("is_default");
            List<String> addressNames = new ArrayList<>();
            List<UserAddress> list = userAddressService.list(qw);
            if(list != null){
                for (UserAddress address : list){
                    Estate estate = estateService.findById(address.getEstateId());
                    if(estate != null){
                        address.setEstateName(estate.getEstateName());
                        addressNames.add(estate.getEstateName() + " - " + address.getRoomNo());
                    }else{
                        addressNames.add(address.getReceiverName() + " - " + address.getRoomNo());
                    }
                }
            }
            map.put("addresses",list);
            map.put("address_names",addressNames);
            List<String> estate_names = new ArrayList<>();
            List<Estate> estates = estateService.selectListByColumn("state",0);
            if(estates != null){
                for (Estate estate : estates){
                    estate_names.add(estate.getEstateName());
                }
            }
            map.put("estates",estates);
            map.put("estate_names",estate_names);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",list.size(),map),false,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }


    /**
     * 地址详情
     * @param
     * @throws Exception
     */
    @PostMapping(value="/detail")
    public JSONObject detail(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int address_id = jsonRequest.containsKey("address_id") ? jsonRequest.getInt("address_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户信息不存在"),true,true);
            }

            UserAddress userAddress = userAddressService.findById(address_id);
            if(user_id!= userAddress.getUserId().intValue()){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该信息不属于您！"),true,true);
            }

            map.put("address",userAddress);

            Estate estate = estateService.findById(user.getEstateId());
            if(estate != null){
                map.put("estate_name",estate.getEstateName());
            }

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",map),true,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }


    /** 添加我的地址列表
     * @param
     * @throws Exception
     */
    @PostMapping(value="/add")
    public JSONObject addAddress(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "user/address/add接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int estate_id = jsonRequest.containsKey("estate_id") ? jsonRequest.getInt("estate_id") : 0;
            String receiver = jsonRequest.containsKey("real_name") ? jsonRequest.getStr("real_name") : "";
            String phone_num = jsonRequest.containsKey("phone_num") ? jsonRequest.getStr("phone_num") : "";
            String address = jsonRequest.containsKey("address") ? jsonRequest.getStr("address") : "";
            String room_no = jsonRequest.containsKey("room_no") ? jsonRequest.getStr("room_no") : "";
            boolean is_default = jsonRequest.containsKey("is_default") ? jsonRequest.getBool("is_default") : false;

            User user = userService.findById(user_id);
            if(user == null){
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),false,false);
                return result;
            }

            //如果当前添加的是默认的 就把当前用户所有的地址 默认状态重置成 非默认状态
            if(is_default){
                userAddressService.updateAllAddressToNoDefault(user_id);
            }

            UserAddress userAddress = new UserAddress();
            userAddress.setIsDefault(is_default ? 1 : 0);
            userAddress.setAddress(address);
            userAddress.setPhoneNum(phone_num);
            userAddress.setReceiverName(receiver);
            userAddress.setUserId(user_id);
            userAddress.setState(1);
            userAddress.setRoomNo(room_no);
            Estate estate = estateService.findById(estate_id);
            if(estate!=null){
                userAddress.setPropertyId(estate.getPropertyId());;
            }
            userAddress.setEstateId(estate_id);

            int res = userAddressService.addAddress(user, userAddress);
            if(res > 0){
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"添加成功"),false,false);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"添加失败"),false,false);
            }

        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /** 添加我的地址列表
     * @param
     * @throws Exception
     */
    @PostMapping(value="/edit")
    public JSONObject editAddress(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "user/address/edit： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int estate_id = jsonRequest.containsKey("estate_id") ? jsonRequest.getInt("estate_id") : 0;
            int addid = jsonRequest.containsKey("estate_id") ? jsonRequest.getInt("addid") : 0;
            String receiver = jsonRequest.containsKey("real_name") ? jsonRequest.getStr("real_name") : "";
            String phone_num = jsonRequest.containsKey("phone_num") ? jsonRequest.getStr("phone_num") : "";
            String address = jsonRequest.containsKey("address") ? jsonRequest.getStr("address") : "";
            String room_no = jsonRequest.containsKey("room_no") ? jsonRequest.getStr("room_no") : "";
            String room_areas = jsonRequest.containsKey("room_areas") ? jsonRequest.getStr("room_areas") : "";
            boolean is_default = jsonRequest.containsKey("is_default") ? jsonRequest.getBool("is_default") : false;

            User user = userService.findById(user_id);
            if(user == null){
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),false,false);
                return result;
            }

            //如果当前添加的是默认的 就把当前用户所有的地址 默认状态重置成 非默认状态
            if(is_default){
                userAddressService.updateAllAddressToNoDefault(user_id);
            }

            UserAddress userAddress = userAddressService.findById(addid);
            if(userAddress!=null){
                userAddress.setIsDefault(is_default ? 1 : 0);
                userAddress.setAddress(address);
                userAddress.setPhoneNum(phone_num);
                userAddress.setReceiverName(receiver);
                userAddress.setUserId(user_id);
                userAddress.setState(1);
                userAddress.setRoomNo(room_no);
                Estate estate = estateService.findById(estate_id);
                if(estate!=null){
                    userAddress.setPropertyId(estate.getPropertyId());;
                }
                userAddress.setEstateId(estate_id);
                userAddress.setRoomAreas(Double.parseDouble(room_areas));
                int res = userAddressService.editAddress(user, userAddress);
                try {
                    if(res > 0){
                        result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"修改成功"),false,false);
                    }else{
                        result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"修改失败"),false,false);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"修改失败"),false,false);
                }
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该地址不存在"),false,false);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /** 添加我的地址列表
     * @param
     * @throws Exception
     */
    @PostMapping(value="/delete")
    public JSONObject deleteAddress(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "user/address/edit： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int address_id = jsonRequest.containsKey("address_id") ? jsonRequest.getInt("address_id") : 0;
            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            UserAddress userAddress = userAddressService.findById(address_id);
            if(userAddress ==  null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该地址不存在"),true,true);
            }
            if(userAddress.getUserId() != user_id){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该地址不属于你"),true,true);
            }

            boolean bl = userAddressService.removeById(address_id);
            if(bl){
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"删除成功"),true,true);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"删除失败"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

}
